import { Component, OnInit,Input, Output,EventEmitter } from '@angular/core';
import * as XLSX from 'xlsx';

@Component({
  selector: 'app-upload',
  templateUrl: './upload.component.html',
  styleUrls: ['./upload.component.scss']
})
export class UploadComponent implements OnInit {
  @Input() uploadTitle:string;
  @Input() elementId:string;
  @Input() fileType:string;
  //header
  @Input() mixHeader:string[];
  @Output() inputdata= new EventEmitter<any[]>();
  inputdataAyy:any[];
  fileName = '';
  uploadTitle$ = '外部設計書アップロード';
  constructor() { }

  ngOnInit() {
  }

  inputChange(evt: any) {
    const target: DataTransfer = <DataTransfer>(evt.target);
    const reader: FileReader = new FileReader();

    if(this.fileType){
      if (target.files.length !== 1) throw new Error('Cannot use multiple files');
      this.fileName = target.files[0].name;

reader.onload=(e: any) => {
  this.inputdata.emit([target.files[0]]);
}
    }else{
      if (target.files.length !== 1) throw new Error('Cannot use multiple files');

      this.fileName = target.files[0].name;
      
  
      reader.onload = (e: any) => {
        const bstr: string = e.target.result;
        const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});
  
        /* grab first sheet */
        const wsname: string = wb.SheetNames[1];
        const ws: XLSX.WorkSheet = wb.Sheets[wsname];
  
        this.inputdataAyy = (XLSX.utils.sheet_to_json(ws, {header:this.mixHeader, defval:''}));
  
        this.inputdata.emit(this.inputdataAyy);
  
        evt.target.value="" // 清空
    }


    };
    reader.readAsBinaryString(target.files[0]);
  }

  selectFile(){
    document.getElementById(this.elementId).click();
  }
}
